
$(function(){
    let _deleteIds = null, _action = '/add';
    const convertor = {type:['目录', '菜单', '接口', '静态资源'],locked:['未锁定','已锁定']};
    const alerter = Frame2.alert.init({$div:$('#alertbar')});
    const table = $('#table').bootstrapTable({
        url: _DIR + '/table',
        toolbar:'#formbar',
        pagination: true,
        sidePagination: 'server',//服务器端分页 返回数据 {rows:[],total:1}
        pageNumber: 1,
        pageSize: 15,
        pageList: [15, 20, 50, 100],//分页步进值
        columns: [{checkbox: true, valign: "bottom"},
        {
            showSelectTitle:true,
            field: 'id',
            title: 'ID',sortable:true
        }, {
            field: 'username',
            title: '用户名'
        }, {
            field: 'fullName',
            title: '姓名'
        }, {
            field: 'nikeName',
            title: '昵称'
        }, {
            field: 'dept',
            title: '部门',
            formatter: (value, row, index, field) => {
                return value.name;
            }
        }, {
            field: 'roles',
            title: '拥有角色',
            formatter: (value, row, index, field) => {
                return _handleRole(value);
            }
        }, {
            field: 'loginTimes',
            title: '登陆',
            formatter: (value, row, index, field) => {
                return value + '次';
            }
        }, {
            field: 'host',
            title: 'IP',
            formatter: (value, row, index, field) => {
                return value==null?'离线':value;
            }
        }, {
            title:'操作',
            align: 'center',
            class: 'action',
            formatter:function(value, row, index, field) {
                return '<button type="button" class="btn btn-xs btn-success view" title="点击查看用户详情">查看</button>'
                    +'<button type="button" class="btn btn-xs btn-primary update" >修改</button>'
                    +'<button type="button" class="btn btn-xs btn-warning resetpassword" >重置密码</button>'
                    +'<button type="button" class="btn btn-xs btn-danger del" >删除</button>'
                    +'<button type="button" class="btn btn-xs btn-danger offline" >强制下线</button>';
            },
            events:{
                'click .view': function(e,value,row,index){
                    //alert("查看"+row.id);
                    let view = $('#viewModal');
                    view.find('#view_id').text(row.id);
                    view.find('#view_username').text(row.username);
                    view.find('#view_fullName').text(row.fullName);
                    view.find('#view_nikeName').text(row.nikeName);
                    view.find('#view_loginTimes').text(row.loginTimes);
                    view.find('#view_roleName').text(_handleRole(row.roles));
                    view.find('#view_deptName').text(row.dept.name);
                    view.find('#view_errorTimes').text(row.errorTimes);
                    view.find('#view_errorContinues').text(row.errorContinues);
                    view.find('#view_locked').text(_handleLocked(row.locked));
                    view.find('#view_lockReason').text(row.lockReason);
                    view.find('#view_createTime').text(new Date(row.createTime).Format('yyyy年MM月dd日 hh:mm:ss'));
                    view.find('#view_updateTime').text(new Date(row.updateTime).Format('yyyy年MM月dd日 hh:mm:ss'));
                    view.find('#view_description').text(row.description);

                    view.modal('show');
                },
                'click .update': function(e,value,row,index) {
                    let form = $('#addForm'),modal = $('#addModal');
                    _action = '/update';
                    modal.find('.modal-title').text('修改用户信息');
                    form.find('#addFormPassword').hide();
                    form.find('#addFormError').show();

                    form.data('bootstrapValidator').enableFieldValidators('password', false);
                    form.find("[name='id']").val(row.id);
                    form.find("[name='username']").val(row.username);
                    form.find("[name='fullName']").val(row.fullName);
                    form.find("[name='nikeName']").val(row.nikeName);
                    form.find("[name='deptId']").val(row.deptId);
                    form.find("[name='errorTimes']").text(row.errorTimes);
                    form.find("[name='errorContinues']").text(row.errorContinues);
                    form.find("[name='locked']").val(row.locked);
                    form.find("[name='lockReason']").val(row.lockReason);

                    form.find("[name='role']").each(function(i,ck){ck.checked=false});
                    let roles = row.roles;
                    if (roles && roles.length > 0) {
                        $.each(roles,function (i,val) {
                            document.getElementById("role_"+val.id).checked = true;
                        })
                    }
                    form.find("[name='description']").val(row.description);
                    modal.modal('show');
                    form.data('bootstrapValidator').resetForm();
                    //alert(form.data('bootstrapValidator').isValid())
                },
                'click .resetpassword': function(e,value,row,index){
                    _deleteIds = [row.id];
                    $('#resetpasswordModal').modal('show');
                },
                'click .del': function(e,value,row,index){
                    _deleteIds = [row.id];
                    $('#deleteModal').modal('show');
                },
                'click .offline': function(e,value,row,index){
                    _deleteIds = [row.id];
                    $('#offlineModal').modal('show');
                },
            }
        }],
        queryParams:function(params) {
            let $array = $('#formbar').serializeArray();
            $.each($array, function(index, val) {
                if(val.value && val.value.trim())
                    params[val.name]=val.value.trim();
            });
            return params;
        },
        onClickRow: function(row,$element,field) {

        }
    }).on('click-row.bs.table',function(event,row,$element,field) {
    	event.preventDefault();
    });

    $('#listbar').on('click', '.add', function(event) {
        event.preventDefault();
        let form = $('#addForm'),modal = $('#addModal');
        form.find('#addFormPassword').show();
        form.find('#addFormError').hide();
        form.data('bootstrapValidator').enableFieldValidators('password', true).resetForm();
        form.data('bootstrapValidator').resetForm();
        form.get(0).reset();
        _action = '/add';
        modal.find('.modal-title').text('创建新用户');
        modal.modal('show');
    });
    $('#listbar').on('click', '.del', function(event) {
        event.preventDefault();
        _deleteIds = Frame2.bootstrap.getSelectionsAttr(table,'id');
        if (_deleteIds == null || _deleteIds.length == 0) {
            alerter.show(100,function(){},{autohide:3000,title:'提示：',content:'请选择要删除的数据！'})
        } else{
            $('#deleteModal').modal('show');
        };
    });
    //确认删除事件
    $('#deleteModal').on('click', '.del', function(event) {
        event.preventDefault();
        $.ajax({
            url: _DIR + '/delete',
            type: 'POST',
            dataType: 'json',
            traditional:true,
            data: {ids: _deleteIds},
            success: function(result) {
                $('#deleteModal').modal('hide');
                if (result.code == 200) {
                    alerter.show(100,function(){},{autohide:3000,content:'数据删除成功。'})
                    table.bootstrapTable('refresh');
                } else{
                    alerter.show(100,function(){},{autohide:5000,content:result.message})
                };
            },complete: function(){
                _deleteIds = [];
            }
        });
    });
    //确认重置密码事件
    $('#resetpasswordModal').on('click', '.del', function(event) {
        event.preventDefault();
        $.ajax({
            url: _DIR + '/resetpassword',
            type: 'POST',
            dataType: 'json',
            traditional:true,
            data: {id: _deleteIds[0]},
            success: function(result) {
                alerter.show(100,function(){},{autohide:5000,content:result.message})
            },complete: function(){
                $('#resetpasswordModal').modal('hide');
                _deleteIds = [];
            }
        });
    });
    //确认强制下线事件
    $('#offlineModal').on('click', '.offline', function(event) {
        event.preventDefault();
        $.ajax({
            url: _DIR + '/offline',
            type: 'POST',
            dataType: 'json',
            traditional:true,
            data: {id: _deleteIds[0]},
            success: function(result) {
                alerter.show(100,function(){},{autohide:5000,content:result.message})
            },complete: function(){
                $('#offlineModal').modal('hide');
                _deleteIds = [];
            }
        });
    });
    //新增表单验证+提交
    $('#addForm').bootstrapValidator(Frame2.bootstrap.validatorConfig({
        fields:{
            username: {
                message: '用户名不合法',//默认提示信息
                validators: {
                    notEmpty: {
                        message: '用户名不能为空'
                    },
                    stringLength: {
                        min: 11,
                        max: 11,
                        message: '用户名必须是11位手机号'
                    },
                    regexp: {
                        regexp: /^[1][3,4,5,7,8,9]\d{9}$/,
                        message: '用户名必须是11位手机号'
                    },
                }
            },
            password: {
                message: '密码不能为空',//默认提示信息
                validators: {
                    notEmpty: {
                        message: '密码不能为空'
                    },
                    stringLength: {
                        min: 6,
                        max: 10,
                        message: '密码长度为6-10位字符'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_]+$/,
                        message: '密码只能由字母、数字和下划线组成。'
                    },
                }
            },
            fullName: {
                message: '姓名不能为空',
                validators: {
                    notEmpty: {
                        message: '姓名名不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 10,
                        message: '姓名长度不能小于2位或超过10位'
                    },
                }
            }
        }
    })).on('success.form.bv', function(e) {
        e.preventDefault();
        let form = $(e.target);
        $.ajax({
            url: _DIR + _action,
            type: 'POST',
            dataType: 'json',
            data: form.serialize(),
            success: function(result) {
                if (result.code == 200) {
                    alerter.show(100,function(){},{autohide:3000,content:'操作成功。'})
                    $('#addModal').modal('hide');
                    table.bootstrapTable('refresh');
                } else{
                    alerter.show(100,function(){},{autohide:5000,content:result.message})
                };
            }
        });
        return false;
    });
    $('#formbar').find("[name='fullName']").typeahead({
        minLength: 1,
        source : function(query, process) {
            return $.ajax({
                url : _DIR + '/typeahead',
                type : 'POST',
                dataType : 'json',
                data : {
                    fullName : query.trim(),
                    limit : 8
                },
                success : function(result) {
                    return process(result);
                }
            });
        },
        //默认获取item.name属性
        displayText : function(item) {
            return item.name;
        },
        delay : 500
    });


    // 解析器
    function _handleRole(roles) {
        if (!roles || !roles.length)
            return "-";
        let result = [];
        $.each(roles,function (i,val) {
            result.push(val.name);
        })
        return result.join(',');
    }
    function _handleLocked(value) {
        return convertor.locked[value];
    }
});
